package org.packtracker.server.servlet;

import java.io.IOException;
import java.util.Date;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.packtracker.client.Constants;
import org.packtracker.server.PMF;
import org.packtracker.server.Parser;
import org.packtracker.server.model.PersistentDate;
import org.packtracker.server.model.PersistentPackage;
import org.packtracker.server.service.ServiceFactory;

public class UpdateServlet extends HttpServlet {

	private static final long serialVersionUID = 5730892581427547252L;

	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		doPost(req, resp);
	}

	@SuppressWarnings("unchecked")
	public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {

		PersistenceManager pm = PMF.get().getPersistenceManager();

		try {
			String query = "select from " + PersistentPackage.class.getName() + " order by creationDate desc";
			List<PersistentPackage> trackedPackages = (List<PersistentPackage>) pm.newQuery(query).execute();

			if (!trackedPackages.isEmpty()) {

				for (PersistentPackage trackedPackage : trackedPackages) {
					Parser parser = new Parser();

					String oldStatus = trackedPackage.getLastStatus();

					// Update status of package
					parser.parseTracker(trackedPackage).getLastStatus();

					if (!oldStatus.equals(trackedPackage.getLastStatus())) {

						// Don't update if the status has changed to unknown
						// Service may be down
						if (!Constants.UNKNOWN_STATUS.equals(trackedPackage.getLastStatus())) {
							// Persist new status
							pm.makePersistent(trackedPackage);

							ServiceFactory.getNotifyService().notify(trackedPackage);
						}
					}

				}

				// Set last updated date
				PersistentDate persistentDate = new PersistentDate(new Date());
				pm.makePersistent(persistentDate);
			}
		} finally {
			pm.close();
		}
	}
}
